<?php 
namespace app\kaoping\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\View;
class Back extends First{
	public function index(){
		$DataDir = "./public/databak/";
		$db=new \databackup\src\Backup();
		if(input('type')!=''){
			//$db=new \databackup\src\Backup();
			$type=input('type');
			$name=input('name');
			switch ($type) {
				case 'backup':
					$list=$db->dataList();//dump($list);die;die;
					foreach ($list as $k => $v) {
						$db->backup($v['name'],0);
					}
					$mes['state']=200;
					$mes['msg']='数据备份成功';
					break;
				case 'restore':
					//return 100;
					$data[1]['1']=$DataDir.$name;
					$res= $db->setFile($data)->import(0);
					$mes['state']=200;
					$mes['msg']='数据还原成功';
					break;
				case 'delete':
					if (unlink($DataDir.$name)) {
						$mes['state']=200;
						$mes['msg']='删除成功！';
					}else {
						$mes['state']=400;
						$mes['msg']='删除失败！';
					}
					break;
			}
			return json($mes);
		}else{
			$list = $this->MyScandir($DataDir);		
		    $n=1;
		    $arr=array();
			foreach($list as $k=>$v){
				if($k>1){
					$fileTime=getfiletime($v,$DataDir);
					$fileSize=getfilesize($v,$DataDir);
			        $arr[$n]['name']=$v;
					$arr[$n]['fileSize']=$fileSize;
					$arr[$n]['fileTime']=$fileTime;
					$n++;
				}
			}
			return view('index',['list'=>$arr]);
		}
	}

	//下载数据文件
	public function DownloadFile() {
		$fileName="./public/databak/".input('name');
		ob_end_clean();
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		header('Content-Length: ' . filesize($fileName));
		header('Content-Disposition: attachment; filename=' . basename($fileName));
		readfile($fileName);
	}

	private function MyScandir($FilePath='', $Order = 0) {
		$FilePath = opendir($FilePath);
		while (false !== ($filename = readdir($FilePath))) {
			$FileAndFolderAyy[] = $filename;
		}
		$Order == 0 ? sort($FileAndFolderAyy) : rsort($FileAndFolderAyy);
		return $FileAndFolderAyy;
	}
}